2.7 Protectedness transfers across packages, but only within a subclass, and only for objects whose type is that subclass. For a bare-bones illustration, suppose we have class A declared in package APackage:
package APackage;
public class A
{
protected int t;
} // class A
Also, suppose that classes C and D are subclasses of A and that C and D are in a different package from A. Then within class D, the t field is treated as if it were declared in D instead of in A. Here are possible declarations for classes C and D:
import APackage.*;
public class C extends A { }
Programming Exercises 101
Class D is declared in another file. For each of the four accesses of t in the following declaration of class D,
hypothesize whether the access is legal or illegal:
import APackage.*;
public class D extends A
{
public void meth()
{
D d = new D();
d.t = 1; // access 1
t = 2; // access 2
A a = new A();
a.t = 3; // access 3
C c = new C();
c.t = 4; // access 4
} method meth
} // class D
Test your hypotheses by creating and running a project that includes the above files.
 
 
View Solution
 
 
 
<< Back Next >>